//
//  PublishNewsViewController.m
//  ZYHome
//
//  Created by Teplot_03 on 16/7/6.
//  Copyright © 2016年 Teplot_01. All rights reserved.
//

#import "PublicNewsViewController.h"
#import "NewsFooterView.h"
#import "NewsHeaderView.h"
#import "TextContentCell.h"
#import "ImageContentCell.h"
#import "UITableView+SDAutoTableViewCellHeight.h"
#import "ContentEditorViewController.h"
#import "ZLPhotoPickerViewController.h"
#import "ZLPhotoAssets.h"

#import "ChooseActivityVC.h"

@interface PublicNewsViewController ()<UITableViewDataSource,UITableViewDelegate,NewsFooterViewDelegate,BaseContentCellDelegate,NewsHeaderViewDelegate>
{
    NSInteger imgsTotalCount;
    NSInteger imgCurrentProgress;
    NSString *headerText;
    
    //第一段文字作为content
    NSString *firstContent;
    
    //第一张图片地址
    NSString *firstImageUrl;
    
    //所有的图片url地址
    NSMutableArray *imgsAttachments;
}
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;//此数组放置文本内容和图片的url

@property (nonatomic, strong) NSMutableArray *contentArr;//放置文本内容和图片的url

@property (nonatomic, strong) NewsHeaderView *header;
@property (nonatomic, strong) NewsFooterView *footer;

@property (nonatomic, assign) ClickPublicPosition clickpublicPosition;
@property (nonatomic, assign) NSInteger index;

@end

@implementation PublicNewsViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    //在这里处理传过来的值
    if (self.backType == BackTypeCancle) {
        return;
    }
    
    switch (self.clickpublicPosition) {
        case ClickPublicPositionTop:
        {
            //暂时不需要
        }
            break;
            
        case ClickPublicPositionMid:
        {
            //暂时都设置为文本(分两部分处理)
            
            //先将数组中的内容改变
            if (self.changeString&&self.changeString.length>0) {
                [self.dataArray replaceObjectAtIndex:self.index withObject:self.changeString];
                
                TextContentCell *cell = [_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:self.index inSection:0]];
                cell.text = self.changeString;
            }
            
        }
            break;
            
        case ClickPublicPositionBtm:
        {
            if (self.changeString&&self.changeString.length>0) {
                [self.dataArray addObject:self.changeString];
                [self.tableView reloadData];
            }
            
        }
            break;
            
        default:
            break;
    }
    self.changeString = nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.backBarButtonItem= [[UIBarButtonItem alloc]initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:nil action:nil];
    [self dataArray];
    [self initUI];

}

- (void)initUI {
    self.title = @"发布游记";
    imgsAttachments = [NSMutableArray array];
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"发布" style:UIBarButtonItemStylePlain target:self action:@selector(publicNews)];
//    rightItem.tintColor = [UIColor greenColor];
    self.navigationItem.rightBarButtonItem = rightItem;
    [self.view addSubview:self.tableView];
}

#pragma mark - clickActions
- (void)publicNews {
    //判断title是否为空
    if (_header.text.length==0) {
//        [LEEAlert alert].system.config.LeeTitle(@"标题不能为空").LeeCancelButtonTitle(@"确定").LeeShow();
        return;
    }
    [self.header endInput];
    
    //发请求之前，要先将图片上传到服务器，然后将url放在数组中
    [SVProgressHUD show];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeGradient];
    //上传图片
    [self uploadImgsToServer];
}

- (void)uploadImgsToServer {
    [imgsAttachments removeAllObjects];
    //先获取第一个文本
    for (id imgsAndText in _dataArray) {
        if ([imgsAndText isKindOfClass:[NSString class]]) {
            firstContent = (NSString *)imgsAndText;
            break;
        }
    }
    //分两种情况，第一种，有图片，第二种没有图片
    //在发请求之前，要先将图片的个数确定一下
    
    imgsTotalCount = 0;
    for (id imgOrText in _dataArray) {
        if ([imgOrText isKindOfClass:[UIImage class]]) {
            imgsTotalCount++;
        }
    }
    
    if (imgsTotalCount == 0) {
        //直接发请求
        
        [self requestPublicNews];
    }
    
    for (int i = 0; i<_dataArray.count; i++ ) {
        id imgsAndText = _dataArray[i];
        
        //如果有图片的话就先上传图片，然后再发请求
        if ([imgsAndText isKindOfClass:[UIImage class]]) {
            UIImage *img = (UIImage *)imgsAndText;
            NSData *imgData = UIImagePNGRepresentation(img);
            
            AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
            manager.requestSerializer=[AFHTTPRequestSerializer serializer];
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            
            [manager POST:@"http://115.28.152.130/tour/v1/travel/imgUpload.action" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
                [formData appendPartWithFileData:imgData name:@"file" fileName:[self getImgFileName] mimeType:@"image/png"];
            } success:^(NSURLSessionDataTask *task, id responseObject) {
                
                NSDictionary *imgUrlDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
                NSLog(@"<<<<<%@",imgUrlDic);
                
                NSString *imgUrl = imgUrlDic[@"imgUrl"];
                //图片上传成功，将图片url替换到数组中
                
                [imgsAttachments addObject:[NSString stringWithFormat:@"%@",imgUrl]];
                [_dataArray replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%@",imgUrl]];
                // 并判断是否为最后一个，如果是最后一个，再发送发送动态的请求
                imgCurrentProgress++;
                if (imgCurrentProgress == imgsTotalCount) {
                    
                    //发动态了
                    
                    [self requestPublicNews];
                }
                
                
            } failure:^(NSURLSessionDataTask *task, NSError *error) {
                [SVProgressHUD showErrorWithStatus:@"请检查网络问题"];
            }];
        }
    }
}

- (void)requestPublicNews{
    //发动态请求
    BOOL hadImg = imgsAttachments.count;
    NSString *firstImg = hadImg?imgsAttachments[0]:@"";
    NSMutableString *mutStr = [[NSMutableString alloc]init];
    for (int i = 0; i<imgsAttachments.count; i++) {
        [mutStr appendString:imgsAttachments[i]];
        if(i!=imgsAttachments.count-1){
            [mutStr appendString:@"##"];
        }
    }
    //把数组中的元素拼接成字符串
    
//    NSString *contentStr = [[NSString alloc]init];
    _contentArr = [[NSMutableArray alloc]init];
    for (int i = 0; i<_dataArray.count; i++) {
        if ([_dataArray[i] hasPrefix:@"http:"]) {
            NSMutableString *str = [NSMutableString stringWithString:_dataArray[i]];
//            [str insertString:@"<img src=" atIndex:0];
//            [str appendFormat:@" />"];
            
            NSString *newString = [NSString stringWithFormat:@"<img src=\"%@\" style=\"width: 100%%;\" />",str];

            NSLog(@"%@<<<<<",str);
            [_contentArr addObject:newString];
        }else{
            NSMutableString *str = [NSMutableString stringWithString:_dataArray[i]];
            [str insertString:@"<p>" atIndex:0];
            [str appendFormat:@"</p>"];
            NSLog(@"%@<<<<<",str);
            [_contentArr addObject:str];
        }

    }
    NSString *contentStr = [_contentArr componentsJoinedByString:@""];
    NSLog(@"%@<<<<<",contentStr);
    NSDictionary *parameter = @{
                                @"title": _header.text,
//                                @"author": @"这是一个作者名",
//                                @"content": _dataArray,
                                @"content": contentStr,
                                @"firstContent": firstContent,
                                @"activityID" : [NSString readToNSDefaultsWithKey:kPAID],
                                @"thumbs" : firstImg,//thumbs 原先 写的是 mutStr
                                @"clubID": [NSString readToNSDefaultsWithKey:kClubId]
                                };
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [@"" saveToNSDefaultsWithKey:kPAID];
    [manager POST:@"http://115.28.152.130/tour/v1/travel/create.action" parameters:parameter success:^(NSURLSessionDataTask *task, id responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@>>>>",dic);
        [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeNone];
        NSString *code = dic[@"code"];
        if (![code isEqualToString:@"0000"]) {
            [SVProgressHUD showErrorWithStatus:[NSString errorStringWithCode:code]];
        }
        else {
            [SVProgressHUD showSuccessWithStatus:@"发布游记成功"];
            [self performSelector:@selector(backToLastCtr) withObject:nil afterDelay:1.3];
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeNone];
        [SVProgressHUD showErrorWithStatus:@"网络异常"];
    }];
}

- (NSString *)getImgFileName {
     NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
     formatter.dateFormat = @"yyyyMMddHHmmss";
     NSString *str = [formatter stringFromDate:[NSDate date]];
     NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
     return fileName;
}

- (void)backToLastCtr {
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - tableView delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    //先从数组中取出数据
    id content = self.dataArray[indexPath.row];
    //如果取出的是字符串
    if ([content isKindOfClass:[NSString class]]) {
        TextContentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TextContentCell"];
        cell.delegate = self;
        cell.text = (NSString *)content;
        return cell;
    }
    //如果取出的是图片
    else if ([content isKindOfClass:[UIImage class]]) {
        ImageContentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ImageContentCell"];
        cell.delegate = self;
        cell.img = (UIImage *)content;
        return cell;
    }
    
    else {
        return nil;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    //先判断是哪一种cell
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    if ([cell isKindOfClass:[TextContentCell class]]) {
        [self presentViewController:[self createContentEditorControllerWithClickPubVCPosition:ClickPublicPositionMid index:indexPath] animated:YES completion:nil];
    }
    else if ([cell isKindOfClass:[ImageContentCell class]]) {
        self.index = indexPath.row;
        [self openAssetsWithIsAddItems:NO];
    }
    
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    _header = [NewsHeaderView new];
    _header.text = headerText;
    [_header.button addTarget:self action:@selector(chooseAction) forControlEvents:UIControlEventTouchUpInside];
    _header.delegate = self;
    return _header;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    _footer = [NewsFooterView new];
    _footer.delegate = self;
    return _footer;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 80;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 40;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 80;
}

#pragma mark - **************** newsHeader delegate
- (void)newsHeaderViewdidEndEditing:(NewsHeaderView *)newsHeaderView {
    headerText = newsHeaderView.text;
}

#pragma mark - newsHeader newsFooter delegate

- (void)newsFooterView:(NewsFooterView *)newsFooterView indexOfClicked:(NSInteger)index {
    switch (index) {
        case 0:
        {
            [self openAssetsWithIsAddItems:YES];
        }
            break;
            
        case 1:
        {
            [self presentViewController:[self createContentEditorControllerWithClickPubVCPosition:ClickPublicPositionBtm index:nil] animated:YES completion:nil];
        }
            break;
            
        default:
            break;
    }
    
}

- (void)addImages:(NSArray *)images {
    //将选到的图片放到数组中
    
    [self.dataArray addObjectsFromArray:images];
    
    [self.tableView reloadData];
}

- (void)exchangeImages:(NSMutableArray *)images {
    [self.dataArray replaceObjectAtIndex:self.index withObject:images.firstObject];
    [images removeObjectAtIndex:0];

    [self.dataArray addObjectsFromArray:images];
    [self.tableView reloadData];
}

- (void)openAssetsWithIsAddItems:(BOOL)isAddItems {
    //跳转到相册
    ZLPhotoPickerViewController *pickerVc = [[ZLPhotoPickerViewController alloc] init];
    // MaxCount, Default = 9
    pickerVc.maxCount = 9;
    // Jump AssetsVc
    pickerVc.status = PickerViewShowStatusCameraRoll;
    // Filter: PickerPhotoStatusAllVideoAndPhotos, PickerPhotoStatusVideos, PickerPhotoStatusPhotos.
    pickerVc.photoStatus = PickerPhotoStatusPhotos;
    pickerVc.topShowPhotoPicker = YES;
    pickerVc.isShowCamera = YES;
    // CallBack
    __weak typeof(pickerVc) weakPickerVc = pickerVc;
    pickerVc.callBack = ^(NSArray<ZLPhotoAssets *> *status){
        //要先将图片压缩一下
        NSMutableArray *images = [NSMutableArray array];
        for (ZLPhotoAssets *photo in status) {
            [images addObject:photo.aspectRatioImage];
        }
        if (isAddItems) {
            [self addImages:images];
        }
        else {
            [self exchangeImages:images];
        }
        
        [weakPickerVc dismissViewControllerAnimated:YES completion:nil];
    };
    [pickerVc showPickerVc:self.navigationController];
}

#pragma mark - baseContent delegate
- (void)baseContentCell:(BaseContentCell *)contentCell deleteBtnClick:(UIButton *)deleteBtn {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:contentCell];
    [_dataArray removeObjectAtIndex:indexPath.row];
    [_tableView reloadData];
}

#pragma mark - lazy load
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.backgroundColor = superBackgroundColor;
        _tableView.frame = [[UIScreen mainScreen] bounds];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        
        [_tableView registerClass:[TextContentCell class] forCellReuseIdentifier:@"TextContentCell"];
        [_tableView registerClass:[ImageContentCell class] forCellReuseIdentifier:@"ImageContentCell"];
        
        [self addHideKeyboardWithTableView:_tableView];
    }
    return _tableView;
}

- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
        [_dataArray addObject:@"添加一段文字"];
    }
    return _dataArray;
}

- (UINavigationController *)createContentEditorControllerWithClickPubVCPosition:(ClickPublicPosition)publicPosition index:(NSIndexPath *)index{
    self.clickpublicPosition = publicPosition;
    
    ContentEditorViewController *vc = [[ContentEditorViewController alloc] init];
    vc.pubNewsVC = self;
    if (index) {
        self.index = index.row;
        vc.text = [self.dataArray objectAtIndex:index.row];
    }
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
    return nav;
}
//选择活动按钮
- (void)chooseAction{
    ChooseActivityVC *vc = [[ChooseActivityVC alloc]init];
    vc.button = _header.button;

    [self.navigationController pushViewController:vc animated:YES];
}
//键盘消失
-(void)addHideKeyboardWithTableView:(UITableView *)tableView
{
    UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
    [tableView addGestureRecognizer:gestureRecognizer];
    gestureRecognizer.cancelsTouchesInView = NO;
}

- (void) hideKeyboard {
    [self.view endEditing:YES];
}

@end
